package model

import (
	"gorm.io/gorm"
)

type (
	StudentModel interface {
		Add(student *Student) (bool, error)
		Login(StudentNo string, Password string) (bool, error)
		IsExit(StudentNo string) (bool, error)
		CtoS(ClassNo string) ([]Student, error)
		FindforID(StudentNo string) (uint, error)
	}

	defaultStudentModel struct {
		conn *gorm.DB
	}

	Student struct {
		gorm.Model
		StudentNo   string   `json:"studentno"   gorm:"type:varchar(10); not null;unique"`
		StudentName string   `json:"studentname" gorm:"type:varchar(255)"`
		Password    string   `json:"password"    gorm:"type:varchar(20); not null"`
		AcademyName string   `json:"academyname" gorm:"type:varchar(255)"` //学院
		ClassNo     string   `json:"classno"     gorm:"type:varchar(10)"`
		ClassName   string   `json:"classname"   gorm:"type:varchar(255)"` //班级
		Result      []Result `json:"result"`
	}
)

func NewStudentModel(conn *gorm.DB) StudentModel {
	//如果没有表则自动构建表
	conn.AutoMigrate(&Student{})
	return &defaultStudentModel{
		conn: conn,
	}
}

//添加信息
func (d defaultStudentModel) Add(student *Student) (bool, error) {
	err := d.conn.Model(student).Create(student).Error
	//fmt.Println("账号密码 ", StudentNo, Password, student.Password)
	if err != nil {
		return false, err
	}
	return true, err
}

//登录验证账号密码
func (d defaultStudentModel) Login(StudentNo string, Password string) (bool, error) {
	var student Student
	err := d.conn.Where("student_no = ?", StudentNo).First(&student).Error
	//fmt.Println("账号密码 ", StudentNo, Password, student.Password)
	if student.Password != Password {
		return false, err
	}
	if err != nil {
		return false, err
	}
	return true, err
}

//是否重复
func (d defaultStudentModel) IsExit(StudentNo string) (bool, error) {
	var total int64 = 0
	err := d.conn.Model(&Student{}).Where("student_no = ?", StudentNo).Count(&total).Error
	//fmt.Println("学号", StudentNo, err)
	if err != nil {
		return false, err
	}
	if total == 0 {
		return false, nil
	}
	return true, nil
}

//班级号查找学号
func (d defaultStudentModel) CtoS(ClassNo string) ([]Student, error) {
	var _student []Student
	err := d.conn.Model(&Student{}).Preload("Result").Where("class_no = ?", ClassNo).Find(&_student).Error

	if err != nil {
		return nil, err
	}

	return _student, nil
}

func (d defaultStudentModel) FindforID(StudentNo string) (uint, error) {
	var student Student
	err := d.conn.Model(&Student{}).Where("student_no = ?", StudentNo).Find(&student).Error
	//fmt.Println("学号", StudentNo, err)
	if err != nil {
		return 0, err
	}
	if student.ID == 0 {
		return 0, nil
	}
	return student.ID, nil
}
